package com.cat.controller;

import com.cat.execption.ServiceExecption;
import com.cat.pojo.Student;
import com.cat.service.Impl.StudentServiceImpl;
import com.cat.service.inter.StudentService;
import com.cat.util.ServletUtils;

import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.*;

import static com.cat.util.Constant.loginConstant.*;
import static com.cat.util.ServletUtils.showError;

/**
 * @author HYC kobe524348@gmail.com
 * @name StudentServlet
 * @description 用于处理学生用户的请求
 * @notice none
 * @date 2019/4/2
 */
@MultipartConfig(location = "C:\\Users\\Misterchaos\\Desktop")
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    StudentService serv = new StudentServiceImpl();
    HttpSession sess = null;
    Object result = null;
    Student stu = null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        sess = req.getSession();
        String method = req.getParameter("method");
        System.out.println("com.cat.controler.StudentServlet : request method is " + method);
        if ("register.do".equalsIgnoreCase(method)) {
            //执行注册功能
            register(req, res);
        } else if ("login.do".equalsIgnoreCase(method)) {
            //执行登陆功能
            login(req, res);
        } else if ("myinfo".equalsIgnoreCase(method)) {
            getInfo(req, res);
        } else if ("update.view".equalsIgnoreCase(method)) {
            //转发到myinfo.jsp并显示修改的输入界面
            req.getRequestDispatcher("StudentServlet?method=myinfo&update=do").forward(req, res);
        } else if ("update".equalsIgnoreCase(method)) {
            stu = (Student) sess.getAttribute("login");
            //转发到myinfo,jsp并显示修改后的页面
            if (setLoginUser(req, res, stu.getStudentId())) {
                req.getRequestDispatcher("myinfo.jsp").forward(req, res);
            }
        } else if ("index".equalsIgnoreCase(method)) {
            res.sendRedirect("index.jsp");
        }
    }

    /**
     * @name register
     * @description 用于控制用户注册的流程跳转
     * @notice none
     * @author HYC kobe524348@gmail.com
     * @date 2019/4/2
     */
    private void register(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        Student stu = ServletUtils.Mapping2Stu(req);
        Map<String,String> map =stu.validate();
        if(map.size()>0){
            req.setAttribute("message",map);
            req.getRequestDispatcher("register.jsp").forward(req, res);
        }
        try {
            result = serv.catRegister(stu);
        } catch (ServiceExecption e) {
            showError(req, res, "系统异常：系统无法正常执行注册功能", "请重试，如果尝试次数过多，请联系管理员");
        }
        if (result == ACCOUNT_ALREADY_EXIST) {
            showError(req, res, "注册失败 ： 该账户已经存在", "解决方案 ： 若您已经注册，请直接登陆");
        } else if (result == REGISTER_SUCCESS) {
            req.getRequestDispatcher("upload.do").forward(req, res);
        }
    }

    /**
     * @name login
     * @description 用于控制用户登陆的流程跳转
     * @notice none
     * @author HYC kobe524348@gmail.com
     * @date 2019/4/2
     */
    private void login(HttpServletRequest req, HttpServletResponse res) {
        String stuId = req.getParameter("studentId");
        String pwd = req.getParameter("password");
        result = serv.catLogin(stuId, pwd);

        if (result == ACCOUNT_NOT_FOUND) {
            //账户不存在，输出提示
            showError(req, res, "登陆失败：用户不存在", "解决方案：请检查您的用户名输入是否正确,如果您没有账户，请先注册一个账户");
        } else if (result == PASSWORD_INCRECTE) {
            //登陆不成功，输出提示
            showError(req, res, "登陆失败：密码错误", "解决方案：请检查您的密码输入是否正确");
        } else if (result == LOGIN_SUCCESS) {
            setLoginUser(req, res, stuId);
            if (sess.getAttribute("admin") != null) {
                //管理员，转发到主页
                try {
                    res.sendRedirect("AdminServlet?method=all");
                } catch (IOException e) {
                    throw new ServiceExecption("exception at redirect ");
                }
            } else {
                //转发到个人信息页面
                try {
                    req.getRequestDispatcher("myinfo.jsp").forward(req, res);
                } catch (IOException e) {
                    throw new ServiceExecption("exception at forward ", e);
                } catch (ServletException e) {
                    throw new ServiceExecption("exception at forward ", e);
                }
            }
        }
    }

    /**
     * @name login
     * @description 用于将已登陆用户的信息存储到session中，并且添加登陆用户的类型信息
     * @notice none
     * @author HYC kobe524348@gmail.com
     * @date 2019/4/2
     */
    private boolean setLoginUser(HttpServletRequest req, HttpServletResponse res, String studentId) {
        Student stu = null;
        List<Student> list = serv.findStudent("studentId", studentId);
        if (list.size() > 0) {
            stu = list.get(0);
        }
        req.setAttribute("login", stu);
        sess.setAttribute("login", stu);
        if ("管理员".equalsIgnoreCase(stu.getUserType())) {
            System.out.println("set this user admin");
            req.setAttribute("admin", "true");
            sess.setAttribute("admin", "true");
        }
        return true;
    }


    /**
     * @param req
     * @param res
     * @return boolean
     * @name getInfo
     * @description 用于向用户的个人信息页面提供信息
     * @notice 请注意这个方法是直接将session中当前登陆用户的信息输出，并不会从数据库更新信息
     * @author HYC kobe524348@gmail.com
     * @date 2019/4/2
     */
    private void getInfo(HttpServletRequest req, HttpServletResponse res) {
        req.setAttribute("login",sess.getAttribute("login"));
        if (req.getAttribute("admin") != null) {
            //转发到管理员中心
            try {
                req.getRequestDispatcher("AdminServlet?method=all").forward(req, res);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        } else {
            //转发到个人信息页面
            try {
                req.getRequestDispatcher("myinfo.jsp").forward(req, res);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }
}